﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//using Web.Auth.Helpers;

namespace API.Models.Repository
{
    public class SEC_SESSIONS_Repository : GenericRepository<PartnerDbContext, SEC_SESSIONS>
    {
        public SEC_SESSIONS GetSession(string api_key)
        {
            return _entities.SEC_SESSIONS.SingleOrDefault(r =>
                    r.APIKEY == api_key &&
                    !r.LOGOFF_DATETIME.HasValue);
        }

        /*
        public SEC_SESSIONS GetSession(string EMAIL, string PASSWORD_HASH)
        {
            var user = _entities.SEC_USERS.SingleOrDefault(r => r.EMAIL == EMAIL);

            var session = _entities.SEC_SESSIONS
                .Include("USER")
                .Include("USER.COMPANIES")
                .Include("USER.COMPANIES.COMPANY")
                .Include("COMPANY")
                .SingleOrDefault(r => r.USER_GUID == user.GUID_RECORD);

            return session;
        }
        */

        /*
        public SEC_SESSIONS GetLastSession()
        {
            var session = _entities.SEC_SESSIONS
                .Include("USER")
                .Include("USER.COMPANIES")
                .Include("USER.COMPANIES.COMPANY")
                .Include("COMPANY")
                .OrderByDescending(r => r.LOGON_DATETIME)
                .FirstOrDefault();

            return session;
        }
        */

        /*
        public void SetActiveCompany(SEC_SESSIONS SESSION, WH_COMPANIES COMPANY)
        {
            SESSION.COMPANY_GUID = COMPANY.GUID_RECORD;

            this.Edit(SESSION);
            this.Save();
        }
        */

        /*
        public void SetSession(Guid USER_GUID, Guid COMPANY_GUID)
        {
            var session = this.Find(r => r.USER_GUID == USER_GUID).SingleOrDefault();

            if (session == null)
            {
                session = new SEC_SESSIONS()
                {
                    GUID_RECORD = Guid.NewGuid(),
                    USER_GUID = USER_GUID,
                    COMPANY_GUID = COMPANY_GUID,
                    LOGON_DATETIME = DateTime.Now
                };

                this.Add(session);
                this.Save();
            }
            else
            {
                session.COMPANY_GUID = COMPANY_GUID;
                session.LOGON_DATETIME = DateTime.Now;
                this.Edit(session);
                this.Save();
            }
        }
        */

        public SEC_SESSIONS LogIn(string ip, string email, string password)
        {
            if (String.IsNullOrEmpty(email))
                throw new Exception("Не указан email");

            if (String.IsNullOrEmpty(password))
                throw new Exception("Не указан пароль");

            var password_hash = API.Core.Util.GetMD5(password);
            var api_key = API.Core.Util.GetMD5(Guid.NewGuid().ToString());

            var user = _entities.SEC_USERS.Where(r =>
                r.EMAIL == email &&
                r.PASSWORD_HASH == password_hash).FirstOrDefault();

            if (user == null)
                throw new Exception("Пользователь не найден");

            var allow_companies = _entities.SEC_USER_COMPANIES
                .Include("COMPANY")
                .Where(r =>
                    r.USER_GUID == user.GUID_RECORD &&
                    r.IS_ALLOWED)
                .Select(r => r.COMPANY)
                .ToList();

            var last_session = _entities.SEC_SESSIONS
                .Include("COMPANY")
                .Where(r =>
                    r.USER_GUID == user.GUID_RECORD)
                .OrderByDescending(r => r.LOGON_DATETIME)
                .FirstOrDefault();

            var company = new WH_COMPANIES
            {
                GUID_RECORD = Guid.Empty,
                COMPANY_NAME = "Компания не выбрана"
            };

            if (allow_companies.Any())
                company = allow_companies.FirstOrDefault();

            if (last_session != null)
                if (allow_companies.Contains(last_session.COMPANY))
                    company = last_session.COMPANY;

            var session = new SEC_SESSIONS
            {
                GUID_RECORD = Guid.NewGuid(),
                USER_GUID = user.GUID_RECORD,
                //COMPANY_GUID = company.GUID_RECORD == Guid.Empty ? new Guid?() : company.GUID_RECORD,
                COMPANY_GUID = company.GUID_RECORD,
                LOGON_DATETIME = DateTime.Now,
                IP = ip,
                APIKEY = api_key
            };

            this.Add(session);
            this.Save();

            session.USER = user;
            session.COMPANY = company;

            return session;
        }

        public SEC_SESSIONS LogIn(string ip, string api_key)
        {
            var session = _entities.SEC_SESSIONS
                .Include("USER")
                .Include("COMPANY")
                .SingleOrDefault(r =>
                    r.APIKEY == api_key &&
                    r.IP == ip &&
                    !r.LOGOFF_DATETIME.HasValue);

            return session;
        }


        public void LogOut(Guid apiKey)
        {

        }
    }
}